<?php
/**
 * --------------------------------------------------------------
 * 权限规则模型
 * --------------------------------------------------------------
 * Light Year Doc
 * @author yinq<3331653644@qq.com>
 * --------------------------------------------------------------
 */
namespace app\admin\model;

use think\Loader;
use think\Model;
use util\Tree;

class AuthRule extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 条件查询
     * @param array $map
     * @param string|boolean $field
     * @param string $type
     * @param string $orderby
     * @param string $limit
     * @return array
     */
    public static function queryOneOrList($map = [], $field = true, $type = 'one', $orderby = 'id desc', $limit = '')
    {
        if ($type == 'one') {
            $object = self::where($map)->field($field)->find();
        } elseif ($type == 'list') {
            if (empty($limit)) {
                $object = self::where($map)->field($field)->order($orderby)->select();
            } else {
                $object = self::where($map)->field($field)->order($orderby)->limit($limit)->select();
            }
        }
        
        return $object ? object_to_array($object) : null;
    }

    /**
     * 获取指定节点ID的位置
     * @param string $id 节点id，如果没有指定，则取当前节点id
     * @param bool $del_last_url 是否删除最后一个节点的url地址
     * @param bool $check 检查节点是否存在，不存在则抛出错误
     * @author 蔡伟明 <314013107@qq.com>
     * @return array
     */
    public static function getLocation ($id = '', $del_last_url = false, $check = true)
    {
        $model      = request()->module();
        $controller = Loader::parseName(request()->controller());
        $action     = request()->action();

        $cache_name = 'location.' . $model . '_' . $controller . '_' . $action;
        $location   = cache($cache_name);
        if (!$location) {
            $map = [
                //['pid', '<>', 0],
                ['name', '=', strtolower($model . '/' . $controller . '/' .$action)]
            ];

            // 当前操作对应的节点ID
            $curr_id = $id == '' ? self::where($map)->value('id') : $id;

            // 获取节点ID所有父级节点
            $location = Tree::getParents(self::column('id,pid,title,name'), $curr_id);

            if ($check && empty($location)) {
                return 0;
            }

            // 剔除最后一个节点url
            if ($del_last_url) {
                $location[count($location) - 1]['url_value'] = '';
            }

            $location = list_to_tree($location, $pk = 'id', $pid = 'pid', 'children');

            // 非开发模式，缓存节点位置信息
            if (config('app.site_setting.develop_mode') == 0) {
                cache($cache_name, $location);
            }
        }

        return $location;
    }

    /**
     * 后台右侧菜单
     * @return array
     */
    public static function getSidebar()
    {
        $sidebar = session('admin_sidebar');
        if (empty($sidebar)) {
            if (AID == 1) {
                // 预留超级管理员账号
                $map = [
                    ['status', '=', 1],
                    ['type', 'in', [1, 2, 4]]
                ];
            } else {
                $Auth   = new \think\Auth();
                // 获取用户所在的用户组
                $groups = $Auth->getGroups(AID);
                $ids    = [];
                if (count($groups) < 1) {
                    $this->error('你没有系统的任何访问权限', url('login/logout'));
                }
                foreach ($groups as $g) {
                    $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
                }
                $ids = array_unique($ids);
                $map = [
                    ['id', 'in', $ids],
                    ['status', '=', 1],
                    ['type', 'in', [1,2,4]]
                ];
            }
            $rules = self::where($map)->field('id,pid,name,title,type,icon')->order('sort', 'asc')->select();
            $rules = object_to_array($rules);
            foreach ($rules as $rid => $rules_one) {
                if ($rules_one['type'] == 1) {
                    // 目录
                } elseif ($rules_one['type'] == 2) {
                    // 菜单
                    $rules[$rid]['url'] = url($rules_one['name']);
                } elseif ($rules_one['type'] == 3) {
                    // 按钮
					$rules[$rid]['url'] = url($rules_one['name']);
                } elseif ($rules_one['type'] == 4) {
                    // 外链
                    $rules[$rid]['url'] = $rules_one['name'];
                }
            }
            $sidebar = list_to_tree_two($rules, $pk = 'id', $pid = 'pid', 'children');

            // 非开发模式，缓存左侧菜单内容
            if (config('app.site_setting.develop_mode') == 0) {
                session('admin_sidebar', null);
                session('admin_sidebar', $sidebar);
            }
        }

        return $sidebar;
    }
}